package com.gack.netty.clientTest;

import com.gack.netty.constant.ClientRequestMessageType;
import com.gack.netty.util.protoBuildUtil.MessageBuildUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 
* @ClassName: NettyClientHeartbeatHandler 
* @Description: TODO(客户端心跳检测 客户端写超时时会想服务端信息心跳请求) 
* @author (ZhangXinYu)  
* @date 2018年8月30日 下午9:54:27 
* @version V1.0
 */
public class NettyClientHeartbeatHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent){
			IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
			if(idleStateEvent.state() == IdleState.WRITER_IDLE){
				// 客户端写超时 向服务端发送心跳包 注：客户端写超时时间需要比服务端读超时时间少一秒或几秒以保证不被服务端认为心跳超时而关闭连接
				 ctx.channel().writeAndFlush(MessageBuildUtil.buildMessage(ClientRequestMessageType.CLIENT_HEARTBEAT_REQUEST, "heartbeat"));
			}
		}
	}

}
